package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author 花木凋零成兰
 * @date 2024/3/11 20:27
 */
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;  // 类型转换
            Method method = handlerMethod.getMethod();  // 获取拦截的方法 反射
            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);    // 获取方法注解
            if (loginRequired != null && hostHolder.getUser() == null) {    // 若为LoginRequired注解标记的方法 且用户没登陆
                response.sendRedirect(request.getContextPath() + "/login");  // 重定向到登录页面
                return false;
            }
        }

        return true;
    }
}
